<template>
  <div class="sxkjjob">
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.sxkjjob_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning" size="small" plain v-if="permissionList" icon="el-icon-upload1" @click="handleExport">导 出</el-button>
      </template>
      <!-- JSA编号 -->
      <template slot="jsaNameForm">
        <div>
          <el-input class="jsa_no" v-model="jsaName"></el-input>
          <el-button type="primary" icon="el-icon-plus" @click="openJsa()" style="margin-left: 50px">选择</el-button>
        </div>
      </template>
      <!--  作业单位名称-->
      <template slot="zydwmcForm">
        <div v-if="zylxType">
          <avue-input-tree default-expand-all v-model="zydwmc" placeholder="请选择内容" type="tree" :dic="deptData" :props="defaultProps"></avue-input-tree>
        </div>
        <div v-else>
          <avue-select v-model="zydwmc" placeholder="请选择内容" type="select" :dic="dic"></avue-select>
        </div>
      </template>

      <!-- 自定义（有毒有害介质、可燃气、氧含量）表格-->
      <template slot="fxbzForm">
        <div>
          <avue-crud :option="fxoption"
                     :data="jzDate">
            <template slot="ydyhjz" slot-scope="scope">
              <el-input v-model="jzDate.ydyhjz" width="auto"></el-input>
            </template>
            <template slot="krq" slot-scope="scope">
              <el-input v-model="jzDate.krq" width="auto"></el-input>
            </template>
            <template slot="yhl" slot-scope="scope">
              <el-input v-model="jzDate.yhl" width="auto"></el-input>
            </template>
          </avue-crud>
        </div>
      </template>
      <!--      证书-->
      <template slot="tsgzzsForm">
        <div v-if="zsData.length>1">
          <avue-crud :option="zsoption"
                     :data="zsData">
            <template slot="cz" slot-scope="scope">
              <div>
                <el-button
                  type="danger"
                  size="small"
                  @click="delZS(scope.row.$index)"
                  icon="el-icon-delete"
                >
                  删除
                </el-button>
              </div>
            </template>
          </avue-crud>
        </div>
      </template>
      <template slot="tsgzzsanForm">
        <div style="margin-left: 300px">
          <el-button
            type="primary"
            size="small"
            @click="addZS()"
            icon="el-icon-plus">
            涉及特殊工种证书
          </el-button>
        </div>
      </template>
      <!-- 危害辨识 -->
      <template slot="whbsForm">
        <div>
          <el-checkbox-group v-model="form1" >
            <el-checkbox v-for="wh in whbs" :label="wh.label" :key="wh.key" @change="funWh(wh.label)"></el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      <!--      安全措施-->
      <template slot="aqcsForm">
        <div>
          <avue-crud :option="aqcsoption"
                     :data="aqcsdata">
            <template slot="aqcs" slot-scope="scope">
              <div style="margin-top: 11px">
                <el-col :span="19">
                  <el-input v-model="aqcsdata[scope.row.$index].cs" width="auto"></el-input>
                </el-col>
                <avue-radio v-model="aqcsdata[scope.row.$index].state" :dic="dic" style="padding-top: 4px"></avue-radio>
              </div>
            </template>
          </avue-crud>
        </div>
      </template>
      <!--防护用品-->
      <template slot="fhypForm">
        <div>
          <el-checkbox-group v-model="fhyps" >
            <el-checkbox v-for="tszy in fhyp" :label="tszy.label" :key="tszy.key"></el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      <!-- 上传交底文件-->
      <template slot="scaqjdwjForm">
        <div v-if="dialogType !== 'view'">
          <el-upload
            action="/api/fileManager/upload/file"
            accept=".pdf,.mp4,.flv"
            :headers="SetHeaders"
            :file-list="fjFileList"
            :before-upload="beforeUploadKJ"
            :on-remove="handleRemoveKJ"
            :on-success="uploadKJSuccess"
          >
            <el-button type="primary">选择文件<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-upload>
        </div>
      </template>
      <!--      审批人-->
      <template slot="sprForm">
        <div>
          <avue-crud :option="sproption"
                     :data="sprData">
            <template slot="splNames" slot-scope="scope">
              <div style="margin-top: 11px">
                <avue-input v-model="sprData[scope.row.$index].splNames" style="width: 380px" readonly></avue-input>
                <el-button type="primary" icon="el-icon-plus" @click="openChoose(scope.row.$index)" style="margin-left: 10px;">选择</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="removespr(scope.row.$index)" >删除</el-button>
              </div>
            </template>
          </avue-crud>
        </div>
      </template>

    </avue-crud>
    <!-- 弹窗：JSA编号选择 -->
    <gcJobJsa
      :jobJsaBox="jobJsaBox"
      @chooseControlMeasure="chooseControlMeasure"
      @cancelChooseControlMeasure="cancelChooseControlMeasure"
      @closeJsa="closeJsa"
    >
    </gcJobJsa>
    <!-- 弹窗：选择审批人员 -->
    <chooseApproveUser
      :chooseApproveUserDialog="chooseApproveUserDialog"
      :selectedUsers="selectedUsers"
      @confirmChooseApproveUser="confirmChooseApproveUser"
      @closeChooseApproveUserDialog="closeChooseApproveUserDialog">
    </chooseApproveUser>
    <chooseZS
      :chooseDialog="chooseDialog"
      :selectedZS="selectedZS"
      @confirmChooseZS="confirmChooseZS"
      @closeChooseDialog="closeChooseDialog">
      ></chooseZS>
  </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove, getfhyp} from "@/api/xcgl/sxkjjob";
  import {mapGetters} from "vuex";
  import {sxkjJobColumn} from "@/views/xcgl/constant/sxkjjob";
  import gcJobJsa from './components/gcJobJsa'
  import {getzylxaqcs} from "@/api/xcgl/measuressetting";
  import {getYjsglxList} from "@/api/xcgl/basejob";
  import {getspr} from "@/api/xcgl/approvalsettings";
  import chooseApproveUser from "@/views/xcgl/components/chooseApproveUser";
  import chooseZS from "@/views/xcgl/components/chooseZS";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getwhcsbz} from "@/api/xcgl/riskprevention";

  export default {
    components:{
      gcJobJsa,
      chooseApproveUser,
      chooseZS
    },
    data() {
      return {
        fhyp:[],
        fhyps:[],
        whcsbzList:[],
        defaultProps: {
          value: 'value', // ID字段名
          label: 'title', // 显示名称
          children: 'children' // 子级字段名
        },
        deptData:[],
        fxoption: {
          menu: false,
          addBtn: false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn: false,
          refreshBtn: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          viewBtn: true,
          selection: false,
          dialogClickModal: false,
          column: [{
            label: "分析项目",
            prop: "fxbz",
            align: "center",

          },
            {
              label: "有毒有害介质",
              prop: "ydyhjz",
              align: "center",
              slot:true,
            },
            {
              label: "可燃气",
              prop: "krq",
              align: "center",
              slot:true,
            },
            {
              label: "含氧量",
              prop: "yhl",
              align: "center",
              slot:true,
            }
            ]
        },
        jzDate:[{
          fxbz:'分析标准',
          ydyhjz:'',
          krq:'',
          yhl:''
        }],

        zsoption: {
          menu: false,
          addBtn: false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn: false,
          refreshBtn: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          selection: false,
          dialogClickModal: false,
          column: [{
            label: "人员名称",
            prop: "rymc",
            align: "center",
            rules: [{
              required: true,
              message: "请输入人员名称",
              trigger: "blur"
            }]
          },
            {
              label: "作业类型",
              align: "center",
              prop: "zylx",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=edu_train_archive_zylx",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number"
            },
            {
              label: "证书编号",
              align: "center",
              prop: "zsbh"
            },
            {
              label: "操作",
              align: "center",
              prop: "cz",
              slot:true
            },
          ]
        },
        selectedZS : [],
        chooseDialog : false,
        zsData:[],
        sprNo:0,
        // 弹窗：选择审批人员
        chooseApproveUserDialog: false,
        selectedUsers: [],
        sprData: [],
        sproption: {
          menu: false,
          addBtn: false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn: false,
          refreshBtn: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          selection: false,
          dialogClickModal: false,
          column: [{
            label: "审批步骤",
            prop: "sphj",
            align: "center",
            type: "select",
            width:250,
            dataType: "number",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=sphj",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
            {
              label: "审批人",
              prop: "splNames",
              align: "center",
              slot:true,
            }]
        },
        zylxType: true,
        zydwmc: '',
        zydwlbType: {
          value: true
        },
        dic: [{
          label: '不涉及',
          value: 0
        }, {
          label: '涉及',
          value: 1
        }],
        aqcsdata: [],
        zylx: 2,
        form1: [],
        whbs: [],
        jsaId: "",
        jsaName: "",
        JSANO: false,
        jobJsaBox: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        aqcsoption: {
          menu: false,
          addBtn: false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn: false,
          refreshBtn: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: false,
          dialogClickModal: false,
          column: [{
            label: "安全措施",
            prop: "aqcs",
            align: "center",
            slot: true,
          }]
        },


        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: sxkjJobColumn,
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.sxkjjob_add, false),
          viewBtn: this.vaildData(this.permission.sxkjjob_view, false),
          delBtn: this.vaildData(this.permission.sxkjjob_delete, false),
          editBtn: this.vaildData(this.permission.sxkjjob_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    watch: {
      'form.zydwlb': {
        handler(val) {
          if (val === 1) {
            this.zylxType = true
            this.zydwmc=''
          } else {
            this.zylxType = false
            this.zydwmc=''
          }
        }
      }
    },
    mounted(){
      this.getwhbs()
      this.getaqcs()
      this.getSPR()
      this.getDept()
      this.getfhyp();
    },
    methods: {

      // handleTemplate() {
      //   window.open(`/api/sxkjjob/export-template?${this.website.tokenHeader}=${getToken()}`);
      // },

      // handleExport() {
      //   this.$confirm("是否导出受限空间作业分析?", "提示", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(() => {
      //     window.open(`/api/sxkjjob/export-sxkjJob?${this.website.tokenHeader}=${getToken()}`);
      //   });
      // },
      getDept(){
        var tenantId = JSON.parse( localStorage.getItem("saber-tenantId") ).content;
        getDeptList(tenantId).then(res => {
          var n= res.data.data;
          this.deptData=n;
        }).then(() => {

        });
      },
      delZS(zsIndex){
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.zsData.splice(zsIndex, 1);
        });
      },
      addZS(){
        if (this.form.zydwlb == '' || this.form.zydwlb == undefined) {
          this.$message.warning("请选择作业单位类别!");
          return;
        }
        this.chooseDialog = true;
      },
      // 确定选择证书
      confirmChooseZS(zsList) {
        console.log(zsList)
        this.zsData = zsList;
        this.closeChooseDialog();
      },
      // 关闭、取消选择证书
      closeChooseDialog() {
        this.selectedZS = [];
        this.chooseDialog = false;
      },
      openChoose(sprNo){
        this.chooseApproveUserDialog=true;
        this.sprNo=sprNo
      },
      // 确定选择审批人员
      confirmChooseApproveUser(userList) {
        this.approveUserData = [];
        var userName=[];
        for(let i = 0 ; i < userList.length ; i++) {
          let item = userList[i];
          let selectUser = {};
          for(var key in item) {
            selectUser[key] = item[key];
          }
          selectUser["shry"] = item.realName;
          this.approveUserData.push(selectUser);
        }
        this.approveUserData.forEach(user=>{
          userName.push(user.shry)
        })
        this.sprData[this.sprNo].splNames=userName.join('|')
        this.closeChooseApproveUserDialog();
      },
      // 关闭、取消选择审批人员弹窗
      closeChooseApproveUserDialog() {
        this.selectedUsers = [];
        this.chooseApproveUserDialog = false;
      },
      //移除审批人
      removespr(index) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.sprData.splice(index, 1);
        });
      },
      //获取审批人
      getSPR() {
        getspr(this.zylx).then(res => {
          this.sprData = res.data.data
          console.log(this.sprData)
        })
      },
      //获取安全措施
      getaqcs() {
        getzylxaqcs(this.zylx).then(res => {
          const n = res.data.data
          n.forEach(aq => aq.state = 0)
          this.aqcsdata = n
        })
      },
      //防护用品
      getfhyp() {
        getfhyp().then(res => {
          for (var i = 0; i < res.data.data.length; i++) {
            this.fhyp[i] =
              {
                label: res.data.data[i].dictValue,
                value: res.data.data[i].dictKey
              }
          }
          console.log(this.fhyp)
        })
      },
      //危害预防措施
      funWh(label,key) {
        if (this.form1 != null) {
          if (this.form.whbscs.indexOf(label) === -1) {
            this.form.whbscs += label + ':'
            var a=1
            for (var i = 0; i < this.whcsbzList.length; i++) {
              if (key == this.whcsbzList[i].whlb) {
                this.form.whbscs+='('+a+')'+' '+this.whcsbzList[i].yfcs
                a++
              }

            }
            this.form.whbscs+= '\n'
          } else {
            var n = this.form.whbscs.slice(this.form.whbscs.indexOf(label), this.form.whbscs.indexOf('\n', this.form.whbscs.indexOf(label) + 1))
            var s = this.form.whbscs.split(n + '\n')
            this.form.whbscs = s.join('')
          }
        }
      },
      //获取危害辨识
      getwhbs() {
        getYjsglxList().then(res => {
          for (var i = 0; i < res.data.data.length; i++) {
            this.whbs[i] =
              {
                label: res.data.data[i].dictValue,
                value: res.data.data[i].dictKey
              }
          }
        })
        getwhcsbz().then(res=>{
          this.whcsbzList=res.data.data
        })
      },
      // 选择
      chooseControlMeasure(list) {
        this.jsaName = list[0].jsaNo
        this.jsaId = list[0].id
        this.cancelChooseControlMeasure();
      },
      // 取消选择JSA编号
      cancelChooseControlMeasure() {
        this.jobJsaBox = false;
      },
      closeJsa() {
        this.jobJsaBox = false
      },
      openJsa() {
        this.jobJsaBox = true
      },

      rowSave(row, done, loading) {
        const aqData = []
        this.aqcsdata.forEach(aq => {
          if (aq.state == 1) {
            aqData.push(aq)
          }
        })
        row.aqcs = aqData
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .sxkjjob {
    .el-form-item__label {
      width: 100px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 100px !important;
      }
    }
  }

  .jsa_no {
    width: calc(100% - 130px);
  }

  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 180px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 180px !important;
        }
      }
    }
  }
</style>
